package com.cloud.message;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

/**
 * 消息生成器
 *
 * @author yzj
 */
public class MQMessageBuilder<T> {

    /**
     * 消息延迟数组变量
     */
    private final String[] DELAY_ARRAY = "1s,5s,10s,30s,1m,2m,3m,4m,5m,6m,7m,8m,9m,10m,20m,30m,1h,2h".split(",");
    /**
     * 消息标记
     */
    private String tag;
    /**
     * 消息内容
     */
    private T message;
    /**
     * 消息key
     */
    private String key;
    /**
     * 消息延迟等级
     */
    private Integer level;

    public void setMessage(String tag, T message, String key) {
        this.tag = tag;
        this.message = message;
        this.key = key;
    }

    public void setMessage(String tag, T message, String key, DelayLevel level) {
        this.tag = tag;
        this.message = message;
        this.key = key;
        this.level = level.getLevel();
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public T getMessage() {
        return message;
    }

    public void setMessage(T message) {
        this.message = message;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public Message build() {
        if (StringUtils.isEmpty(this.key)) {
            throw new RuntimeException("未定义用于发送此消息的消息键");
        }
        if (ObjectUtils.isEmpty(this.message)) {
            throw new RuntimeException("消息正文不能为空");
        }
        MessageBuilder message = MessageBuilder.withPayload(this.message);
        if (!StringUtils.isEmpty(this.tag)) {
            message.setHeader(MessageConst.PROPERTY_TAGS, this.tag);
        }
        message.setHeader(MessageConst.PROPERTY_KEYS, this.key);
        if (this.level != null && this.level > 0 && this.level <= DELAY_ARRAY.length) {
            message.setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, this.level);
        }
        return message.build();
    }

}
